home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cgazv5n4.arc / STFILE.CPP < prev    next >
C/C++ Source or Header  |  1991-09-23  |  1KB  |  45 lines

  1. //--- STFILE.CPP ------------------------- Listing 6 -----------
  2. // Using new to create an array of string pointer objects
  3. // by Bruce Eckel. See Listing 1 for copyright information.
  4. //--------------------------------------------------------------
  5.  
  6. #include "strngptr.h"
  7.  
  8. main(int argc, char * argv[]) {
  9.   if(argc < 2) {
  10.     fprintf(stderr, "usage: stfile filename\n");
  11.     exit(1);
  12.   }
  13.   int lines = 0;
  14.   {  // count the lines in the file
  15.     FILE* fp = fopen(argv[1], "r");
  16.     if(fp == NULL) {
  17.       fprintf(stderr, "could not open %s\n", argv[1]);
  18.       exit(1);
  19.     }
  20.     const bufsize = 80;
  21.     char buf[bufsize];
  22.     while(fgets(buf, bufsize, fp))
  23.       lines++;
  24.     fclose(fp);
  25.   }
  26.   FILE* fp = fopen(argv[1], "r");  // open the file again
  27.   // An array with size determined at run-time:
  28.   string_ptr* sp = new string_ptr[lines];
  29.   // (constructor insures proper initialization of string_ptrs)
  30.   // sp now looks like a normal array (except
  31.   //      that it must be deleted).
  32.  
  33.   const bsz = 80; char buf[bsz];
  34.   for(int i = 0; i < lines; i++) {
  35.     if(!fgets(buf, bsz, fp)) break;  // quit on end-of-file
  36.     buf[strlen(buf) -1] = '\0';  // erase terminating newline
  37.     sp[i]->append(buf);          // append to the empty line
  38.   }
  39.   // Now we have the entire file in an array of string_ptr
  40.   // Perform editing here ...
  41.   // Then you can print out the array:
  42.   for(i = 0; i < lines; i++)
  43.     sp[i]->print();
  44.   delete sp;
  45. }